package com.tre.jdevtemplateboot.common.util;

import com.tre.jdevtemplateboot.domain.bo.HostsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * @author JDev
 */
public class IpConfig {

    private static final Logger logger = LoggerFactory.getLogger(IpConfig.class);

    private IpConfig(){   }

    public static HostsConfig getHostsConfig(){
        InetAddress ia = null;
        HostsConfig hostsConfig = new HostsConfig();
        try {
            ia = InetAddress.getLocalHost();
            if (ia != null){
                hostsConfig.setHostsName(ia.getHostName());
                hostsConfig.setHostsAddress(ia.getHostAddress());
                hostsConfig.setMacAddress(getMACAddress(ia));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return  hostsConfig;
    }

    private static String getMACAddress(InetAddress ia) throws SocketException {
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        return sb.toString().toUpperCase();
    }
}
